package com.onLineCar.dispatch.convertsql;

import java.io.FileWriter;
import java.io.IOException;
import java.lang.reflect.Field;
import java.math.BigDecimal;

/**
 * 将实体类转换为MySQL建表语句并输出到文件中的工具类
 * Author: 木芒果
 */
public class EntityToTableConverter {

    /**
     * 将实体类转换为MySQL建表语句并输出到文件中
     *
     * @param clazz    实体类的Class对象
     * @param filePath 输出文件的路径：如"User.sql",就会在项目根目录下创建一个名为User.sql的文件，文件路径为空则将建表语句输出到控制台
     * @throws IOException 如果输出文件时发生错误
     */
    public static void convertToCreateTableStatement(Class<?> clazz, String filePath) {
        try {
            StringBuilder sb = new StringBuilder();
            sb.append("DROP TABLE IF EXISTS ");
            String simpleName = clazz.getSimpleName();
            sb.append(convertCamelToUnderline(simpleName));
            sb.append(";\n");
            sb.append("CREATE TABLE ");
            sb.append(convertCamelToUnderline(simpleName));
            sb.append(" (\n");

             Field[] fields = clazz.getDeclaredFields();
             for (int i = 0; i < fields.length; i++) {
                Field field = fields[i];
                sb.append("    ");
                String fieldName = field.getName();
                if (fieldName != "serialVersionUID") {
                    sb.append(convertCamelToUnderline(fieldName));
                    sb.append(" ");
                    sb.append(getColumnType(field.getType()));
                    if (fieldName.equals("id")) { // 如果字段名为"id"，则自动设置为主键，自动增长
                        sb.append(" PRIMARY KEY AUTO_INCREMENT");
                    }
                    sb.append(",\n");
                }
            }
            sb.deleteCharAt(sb.lastIndexOf(","));
            sb.append(");");

            if (filePath == null) {
                System.out.println(sb);
                return;
            }
            FileWriter writer = new FileWriter(filePath);
            writer.write(sb.toString());
            writer.close();
            System.out.println("建表语句已输出到" + filePath);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取字段类型对应的MySQL数据类型
     *
     * @param fieldType 字段类型
     * @return MySQL数据类型
     */
    private static String getColumnType(Class<?> fieldType) {
        if (fieldType == String.class) {
            return "VARCHAR(255)";
        } else if (fieldType == int.class || fieldType == Integer.class) {
            return "INT";
        } else if (fieldType == long.class || fieldType == Long.class) {
            return "BIGINT";
        } else if (fieldType == double.class || fieldType == Double.class) {
            return "DOUBLE";
        } else if (fieldType == boolean.class || fieldType == Boolean.class) {
            return "BOOLEAN";
        } else if (fieldType == byte[].class) {
            return "LONGBLOB";
        } else if (fieldType == java.util.Date.class || fieldType == java.sql.Timestamp.class || fieldType == java.time.LocalDateTime.class) {
            return "DATETIME";
        } else if (fieldType == BigDecimal.class) {
            return "DECIMAL(10,2)"; // 可根据需要调整精度和小数位数
        }
        // 如果遇到无法识别的类型，可以根据实际需求进行扩展
        return "VARCHAR(255)";
    }

    /**
     * 将驼峰命名法转换为下划线命名法
     *
     * @param camel 驼峰命名法字符串
     * @return 下划线命名法字符串
     */
    private static String convertCamelToUnderline(String camel) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < camel.length(); i++) {
            char c = camel.charAt(i);
            if (Character.isUpperCase(c)) {
                if (i == 0) {
                    sb.append(Character.toLowerCase(c));
                } else {
                    sb.append('_');
                    sb.append(Character.toLowerCase(c));
                }
            } else {
                sb.append(c);
            }
        }
        return sb.toString();
    }
}
